package com.share.tool.maven.plugin.model;

import com.share.common.utils.EncryptUtil;
import com.share.common.utils.FileUtil;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.util.List;

@Mojo(name = "encryptClassEvent", defaultPhase = LifecyclePhase.PACKAGE)
public class EncryptClass extends AbstractMojo {
    @Parameter(property = "packageName", required = true)
    private String packageName;
    private String packageNameDir;

    @Parameter(property = "outputDirectory", required = true)
    private String outputDirectory;


    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        //参数日志
        System.out.println("加密class文件packageName=" + packageName + ",outputDirectory=" + outputDirectory);

        //值初始化
        packageNameDir = packageName.replaceAll("\\.", File.separator + File.separator); /*这里的替换需要注意正则*/

        //功能逻辑
        List<File> files = FileUtil.listFile(outputDirectory);
        for (File file : files) {
            String fileName = file.getAbsolutePath();
            if (fileName.contains(packageNameDir)) {
                System.out.println("正在加密文件:" + fileName);

                byte[] bytes = FileUtil.readByte(file);
                byte[] encryptBytes = EncryptUtil.encrypt(bytes);
                FileUtil.writeByte(file, encryptBytes);
            }
        }
    }

    public static void main(String[] args) {
        try {
            new EncryptClass().execute();
        } catch (MojoExecutionException e) {
            e.printStackTrace();
        } catch (MojoFailureException e) {
            e.printStackTrace();
        }
    }
}
